#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define nline "\n"
#define Mod 1000000007
#define vi vector<ll>
#define vii vector<pair<ll,ll>>
#define umap unordered_map
#define uset unordered_set
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define rep1(i,a,n) for(ll i=a;i<n;i++)
#define rep2(i,a,n) for(ll i=a;i<=n;++i)
#define rep3(i,n,a) for(ll i=n;i>=a;--i)
#define P pair<ll,ll>
#define ff first
#define ss second
void solve(){
ll n,m,d;
cin>>n>>m>>d;
vector<ll>pos(n+1);
for(ll i=1;i<=n;i++){
ll x;
cin>>x;
pos[x]=i;
}
vector<ll>v2(m+1);
for(ll i=0;i<m;++i){
cin>>v2[i];
}
ll ans=1e8;
for(ll i=0;i<m-1;++i){
if(pos[v2[i]]>pos[v2[i+1]]){
ans=0;
break;
}
else if(pos[v2[i]]+d<pos[v2[i+1]]){
ans=0;
break;
}
else{
ll move=d+1-(pos[v2[i+1]]-pos[v2[i]]);
if(move<=(pos[v2[i]]-1+n-pos[v2[i+1]])){
ans=min(ans,move);
}
ans=min(ans,pos[v2[i+1]]-pos[v2[i]]);
}
}
cout<<ans<<nline;
}
int main(){
ll t;
cin>>t;
while(t--){
solve();
}
}
892A - Greed | 32A - Reconnaissance |
1236D - Alice and the Doll | 1207B - Square Filling |
1676D - X-Sum | 1679A - AvtoBus |
1549A - Gregor and Cryptography | 918C - The Monster |
4B - Before an Exam | 545B - Equidistant String |
1244C - The Football Season | 1696B - NIT Destroys the Universe |
1674A - Number Transformation | 1244E - Minimizing Difference |
1688A - Cirno's Perfect Bitmasks Classroom | 219A - k-String |
952A - Quirky Quantifiers | 451B - Sort the Array |
1505H - L BREAK into program | 171E - MYSTERIOUS LANGUAGE |
630D - Hexagons | 1690D - Black and White Stripe |
1688D - The Enchanted Forest | 1674C - Infinite Replacement |
712A - Memory and Crow | 1676C - Most Similar Words |
1681A - Game with Cards | 151C - Win or Freeze |
1585A - Life of a Flower | 1662A - Organizing SWERC |